import { ref } from 'vue';
import app from '@/app'
import { template as getStore } from '@/api/manage'
import { template, templateUpdate } from '@/api/erp/config'

import base from '@/app/model'

// 继承总模型
const model = new base;

model.get = () => {
  return new Promise((resolve, jeject) => {
    template().then(res => {
      // 按关键字归类
      res.forEach(item => {
        model.getData()[item.keyword] = item
      })
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

model.store = ref({})
model.getStore = () => {
  return new Promise((resolve, jeject) => {
    app.ui.loading()
    getStore().then(res => {
      const store = {}
      // 按关键字归类
      res.forEach(item => {
        const keyword = item.keyword
        if(!store[keyword]) {
          store[keyword] = []
        }
        store[keyword].push(item)
      })
      model.store.value = store
      resolve(res)
    }).catch(res => {
      jeject(res)
    }).finally(() => {
      app.ui.loadingClose()
    })
  })
}

// 设置模版
model.set = data => {
  // 更新配置
  return new Promise((resolve, jeject) => {
    templateUpdate(data).then(res => {
      model.get()
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

// 关键字取出模版
model.getTemplate = name => {
  const template = model.getData()[name]
  return template ?? null
}

// 判断模版选中
model.has = data => {
  // 获取模版
  const template = model.getTemplate(data.keyword)
  return template ? template.id == data.id : false
}

// 判断模版更新
model.hasUpdate = data => {
  // 获取模版
  const template = model.getTemplate(data.keyword)
  if(!template) return template
  // 判断是否同一ID并且内容不一样
  return template.id == data.id && template.html != data.html
}


// 打印模版信息
model.printTemplate = (name) => {
  // 获取模版
  const template = model.getTemplate(name)
  if(!template) return

  // 数据插入模版数据
  const data = {}
  // 循环解析模版数据
  template.data.forEach(item => {
    data[item.key] = item.value
  })

  return { version: template.version, view: template.html, data }
}

export default model